package org.durcframework.rms.controller;

import java.util.ArrayList;
import java.util.List;

import org.durcframework.core.UserContext;
import org.durcframework.core.controller.SearchController;
import org.durcframework.rms.common.UserMenu;
import org.durcframework.rms.entity.RSysFunction;
import org.durcframework.rms.entity.RSysRes;
import org.durcframework.rms.entity.RUser;
import org.durcframework.rms.service.RSysFunctionService;
import org.durcframework.rms.service.RSysResService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class MenuController extends SearchController<RSysRes, RSysResService>{
	
	@Autowired
	private RSysFunctionService sysFunctionService;
	
	/**
	 * 加载用户菜单
	 * @return
	 */
	@RequestMapping("listUserMenu.do")
	public ModelAndView listUserMenu(){
		RUser user = UserContext.getInstance().getUser();
		
		if(user == null){
			return errorView("当前用户不存在");
		}
		
		List<UserMenu> menuList = this.getService().getUserMenu(user.getUsername());
		
		return this.render(menuList);
	}
	
    // 获取所有菜单
	@RequestMapping("/listAllMenu.do")
    public ModelAndView listAllMenu() {
    	List<RSysRes> rows = this.getService().getAllRSysRes();
    	List<RSysRes> treeData = buildTreeData(rows);
		return this.render(treeData);
    }
	
	 // 获取所有菜单
		@RequestMapping("/listRoleMenu.do")
	    public ModelAndView listRoleMenu() {
	    	List<RSysRes> rows = this.getService().getAllRSysRes();
	    	
	    	for (RSysRes res : rows) {
	    		List<RSysFunction> sysFuns = sysFunctionService.getBySySResId(res.getSrId());
				res.setSysFuns(sysFuns);
			}
	    	
	    	List<RSysRes> treeData = buildTreeData(rows);
	    	
	    	return this.render(treeData);
	    }
    
    /**
	 * 构建树形菜单
	 * @param list
	 * @return
	 */
	public static List<RSysRes> buildTreeData(List<RSysRes> list) {

		List<RSysRes> menu = new ArrayList<RSysRes>();

		resolveMenuTree(list, 0, menu);

		return menu;
	}
	
	public static int resolveMenuTree(List<RSysRes> menus, int parentMenuId,
			List<RSysRes> nodes) {

		int count = 0;
		for (RSysRes menu : menus) {
			if (menu.getParentId() == parentMenuId) {
				RSysRes node = new RSysRes();

				nodes.add(node);
				node.setSrId(menu.getSrId());
				node.setResName(menu.getText());
				node.setUrl(menu.getUrl());
				node.setParentId(menu.getParentId());
				node.setChildren(new ArrayList<RSysRes>());
				node.setSysFuns(menu.getSysFuns());

				resolveMenuTree(menus, menu.getId(), node.getChildren());
				count++;
			}
		}
		return count;
	}
	

	
}
